﻿using LJ.FaultHandler.Abstractions;
using LJ.Socket.Data;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LJ.Socket.Server.StraightChicken.Internal;

public class SocketMessageListener(IFaultHandlerFactory faultHandlerFactory, ISocketServerHandlerInvoker socketServerHandlerInvoker, ILogger<SocketMessageListener> logger) : ISocketMessageListener
{
    private readonly IFaultHandlerFactory _faultHandlerFactory = faultHandlerFactory;
    private readonly ISocketServerHandlerInvoker _socketServerHandlerInvoker = socketServerHandlerInvoker;
    private readonly ILogger _logger = logger;

    public async Task<bool> OnReceiveAsync(SocketMessage message, CancellationToken cancellationToken)
    {
        try
        {
            var faultHandler = _faultHandlerFactory.Create();
            await faultHandler.ExecuteAsync(async a => {

                await _socketServerHandlerInvoker.InvokeAsync(message);

            }, cancellationToken);

            return true;
        }
        catch (Exception ex)
        {
            _logger.LogWarning("[SocketServer] SocketMessageListener  {message}", ex.Message);

            return false;
        }
    }
}
